package com.sky.sky_server.aspeck;

import java.time.LocalDateTime;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.sky.sky_common.context.BaseContext;
import com.sky.sky_common.enumeration.OperationType;
import com.sky.sky_server.annotation.AutoFill;
import io.jsonwebtoken.lang.Arrays;
import lombok.extern.slf4j.Slf4j;

@Component
@Aspect
@Slf4j
public class AutofillAspect {
    /**
     * 获取当前登录用户
     */
    public Long getCurrentUserId() {
        return BaseContext.getCurrentId();
    }

    @Pointcut("execution(* com.sky.sky_server.mapper.*.*(..)) && @annotation(com.sky.sky_server.annotation.AutoFill)")
    public void autoFillPointcut() {}

    @Before("autoFillPointcut()")
    public void doBefore(JoinPoint joinPoint) {
        log.info("***************前置通知***************");
        Object[] args = joinPoint.getArgs();
        if(args.length == 0 || args == null) return;
        System.out.println("方法名："+joinPoint.getSignature().getName());
        System.out.println("参数值集合：" + Arrays.asList(joinPoint.getArgs()));
        System.out.println("参数类型集合："+ joinPoint.getArgs()[0].getClass().getTypeName());
        // 获取目标注解对象
        AutoFill autoFill = ((MethodSignature)joinPoint.getSignature()).getMethod().getAnnotation(AutoFill.class);
        String classType = joinPoint.getTarget().getClass().getName();
        System.out.println("目标注解对象："+ autoFill);
        System.out.println("目标注解对象的value: "+ autoFill.value());
        System.out.println("目标注解对象TestValue："+ autoFill.testValue());
        System.out.println("目标方法所在类："+classType);

        log.info("***************开始处理填充***************");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取当前用户
        Long userId = this.getCurrentUserId();
        // 获取当前处理对象
        Object target = args[0];
        try{
            target.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(target, now);
            target.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(target, userId);
            if(autoFill.value() == OperationType.INSERT){
                target.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class).invoke(target, now);
                target.getClass().getDeclaredMethod("setCreateUser", Long.class).invoke(target, userId);
            }
        }catch(Exception e){
            log.error("***************处理填充异常***************");
        }

        log.info("***************前置通知结束***************");


    }

}
